// 肉鸽附加系统 - 完全独立，不影响原有游戏
(function() {
    'use strict';
    
    // 全局配置
    const ADDON_CONFIG = {
        enabled: true,
        debug: true,
        safeMode: true,
        checkInterval: 2000, // 2秒检查一次
        maxRetries: 3
    };
    
    // 肉鸽附加系统
    class RoguelikeAddon {
        constructor() {
            this.active = false;
            this.initialized = false;
            this.retryCount = 0;
            this.lastCheck = 0;
            
            // 游戏状态追踪
            this.gameState = {
                currentLevel: 0,
                lastLevel: 0,
                isPlaying: false,
                playerAlive: true
            };
            
            // 肉鸽数据
            this.rogueData = {
                runCount: this.loadData('runCount', 0),
                totalKills: this.loadData('totalKills', 0),
                bestRun: this.loadData('bestRun', 0),
                permanentUpgrades: this.loadData('permanentUpgrades', {}),
                currentRunStats: this.resetRunStats()
            };
            
            // 延迟启动，确保游戏完全加载
            setTimeout(() => {
                this.safeInitialize();
            }, 5000);
        }
        
        safeInitialize() {
            try {
                if (!ADDON_CONFIG.enabled) return;
                
                this.log('🎲 肉鸽附加系统启动中...');
                
                // 检查游戏是否正常运行
                if (!this.checkGameHealth()) {
                    this.log('⚠️ 游戏未完全加载，稍后重试');
                    this.scheduleRetry();
                    return;
                }
                
                // 启动监控循环
                this.startMonitoring();
                
                this.initialized = true;
                this.active = true;
                this.log('✅ 肉鸽附加系统已激活');
                
            } catch (error) {
                this.log('❌ 肉鸽系统初始化失败:', error.message);
                this.safeShutdown();
            }
        }
        
        checkGameHealth() {
            try {
                // 检查必要的游戏对象
                const requiredObjects = [
                    'window.gameEngine',
                    'window.levelManager', 
                    'window.gameManager',
                    'window.roguelikeSystem'
                ];
                
                for (const objPath of requiredObjects) {
                    const obj = this.getNestedObject(objPath);
                    if (!obj) {
                        this.log(`缺少对象: ${objPath}`);
                        return false;
                    }
                }
                
                return true;
            } catch (error) {
                this.log('游戏健康检查失败:', error.message);
                return false;
            }
        }
        
        getNestedObject(path) {
            try {
                return path.split('.').reduce((obj, key) => obj && obj[key], window);
            } catch (error) {
                return null;
            }
        }
        
        scheduleRetry() {
            if (this.retryCount < ADDON_CONFIG.maxRetries) {
                this.retryCount++;
                setTimeout(() => {
                    this.safeInitialize();
                }, 3000 * this.retryCount);
            } else {
                this.log('❌ 重试次数已达上限，肉鸽系统停止');
            }
        }
        
        startMonitoring() {
            setInterval(() => {
                if (!this.active) return;
                
                try {
                    this.updateGameState();
                    this.checkForEvents();
                } catch (error) {
                    this.log('监控循环错误:', error.message);
                    // 不停止监控，只记录错误
                }
            }, ADDON_CONFIG.checkInterval);
        }
        
        updateGameState() {
            try {
                if (!window.gameEngine || !window.levelManager) return;
                
                const newLevel = window.levelManager.currentLevel || 0;
                const isPlaying = window.gameEngine.gameState === 'playing';
                const playerAlive = window.player ? window.player.health > 0 : true;
                
                // 检测关卡变化
                if (newLevel !== this.gameState.currentLevel) {
                    this.onLevelChange(this.gameState.currentLevel, newLevel);
                    this.gameState.lastLevel = this.gameState.currentLevel;
                    this.gameState.currentLevel = newLevel;
                }
                
                // 检测游戏状态变化
                if (isPlaying !== this.gameState.isPlaying) {
                    this.gameState.isPlaying = isPlaying;
                    if (isPlaying) {
                        this.onGameStart();
                    }
                }
                
                // 检测玩家死亡
                if (this.gameState.playerAlive && !playerAlive) {
                    this.gameState.playerAlive = playerAlive;
                    this.onPlayerDeath();
                }
                
                this.gameState.playerAlive = playerAlive;
                
            } catch (error) {
                this.log('状态更新错误:', error.message);
            }
        }
        
        checkForEvents() {
            try {
                // 检查是否应该掉落装备
                if (this.shouldDropEquipment()) {
                    this.dropRandomEquipment();
                }
                
                // 检查是否应该触发升级选择
                if (this.shouldShowUpgradeSelection()) {
                    this.triggerUpgradeSelection();
                }
                
                // 检查是否应该给予奖励
                if (this.shouldGiveReward()) {
                    this.giveRandomReward();
                }
                
            } catch (error) {
                this.log('事件检查错误:', error.message);
            }
        }
        
        onLevelChange(oldLevel, newLevel) {
            try {
                this.log(`🎯 关卡变化: ${oldLevel} -> ${newLevel}`);
                
                if (newLevel > oldLevel && newLevel > 0) {
                    // 关卡完成
                    this.onLevelComplete(oldLevel);
                }
                
                if (newLevel > 0) {
                    // 新关卡开始
                    this.onLevelStart(newLevel);
                }
                
            } catch (error) {
                this.log('关卡变化处理错误:', error.message);
            }
        }
        
        onLevelComplete(level) {
            try {
                this.log(`🏆 关卡 ${level} 完成`);
                
                // 更新统计
                this.rogueData.currentRunStats.levelsCompleted = Math.max(
                    this.rogueData.currentRunStats.levelsCompleted, 
                    level
                );
                
                // 给予金币奖励
                this.giveCoins(20 + level * 5);
                
                // 延迟触发升级选择
                setTimeout(() => {
                    this.triggerUpgradeSelection();
                }, 2000);
                
                this.saveAllData();
                
            } catch (error) {
                this.log('关卡完成处理错误:', error.message);
            }
        }
        
        onLevelStart(level) {
            try {
                this.log(`🎮 关卡 ${level} 开始`);
                
                // 应用永久升级
                this.applyPermanentUpgrades();
                
                // 安排装备掉落
                this.scheduleEquipmentDrops(level);
                
                // 显示关卡提示
                this.showLevelHint(level);
                
            } catch (error) {
                this.log('关卡开始处理错误:', error.message);
            }
        }
        
        onGameStart() {
            try {
                this.log('🎮 游戏开始');
                
                // 重置当前轮次统计
                this.rogueData.currentRunStats = this.resetRunStats();
                
                // 应用永久升级
                this.applyPermanentUpgrades();
                
            } catch (error) {
                this.log('游戏开始处理错误:', error.message);
            }
        }
        
        onPlayerDeath() {
            try {
                this.log('💀 玩家死亡');
                
                // 完成当前轮次
                this.completeRun();
                
                // 给予遗产奖励
                this.giveDeathRewards();
                
                // 增加轮次计数
                this.rogueData.runCount++;
                
                // 显示死亡总结
                this.showDeathSummary();
                
                this.saveAllData();
                
            } catch (error) {
                this.log('玩家死亡处理错误:', error.message);
            }
        }
        
        shouldDropEquipment() {
            try {
                const now = Date.now();
                const timeSinceLastDrop = now - (this.lastEquipmentDrop || 0);
                
                // 每15-30秒随机掉落一次
                if (timeSinceLastDrop > 15000 && Math.random() < 0.3) {
                    this.lastEquipmentDrop = now;
                    return this.gameState.isPlaying;
                }
                
                return false;
            } catch (error) {
                return false;
            }
        }
        
        dropRandomEquipment() {
            try {
                if (!window.gameEngine || !window.gameEngine.powerUps) return;
                
                // 创建简单的装备掉落
                const equipment = {
                    x: Math.random() * 800 + 100,
                    y: Math.random() * 600 + 100,
                    width: 20,
                    height: 20,
                    type: 'roguelike_equipment',
                    name: this.generateEquipmentName(),
                    rarity: this.selectRarity(),
                    collected: false
                };
                
                window.gameEngine.powerUps.push(equipment);
                this.log(`📦 掉落装备: ${equipment.name} (${equipment.rarity})`);
                
            } catch (error) {
                this.log('装备掉落错误:', error.message);
            }
        }
        
        shouldShowUpgradeSelection() {
            try {
                const now = Date.now();
                const timeSinceLastUpgrade = now - (this.lastUpgradeShow || 0);
                
                // 关卡完成后显示升级选择
                return (window.gameEngine && 
                        window.gameEngine.gameState === 'levelComplete' && 
                        timeSinceLastUpgrade > 5000);
            } catch (error) {
                return false;
            }
        }
        
        triggerUpgradeSelection() {
            try {
                this.lastUpgradeShow = Date.now();
                
                if (window.roguelikeSystem && 
                    typeof window.roguelikeSystem.showUpgradeSelection === 'function') {
                    
                    setTimeout(() => {
                        try {
                            window.roguelikeSystem.showUpgradeSelection();
                            this.log('🎲 显示升级选择');
                        } catch (error) {
                            this.log('升级选择显示失败:', error.message);
                        }
                    }, 1000);
                }
                
            } catch (error) {
                this.log('升级选择触发错误:', error.message);
            }
        }
        
        shouldGiveReward() {
            try {
                // 随机奖励触发
                return Math.random() < 0.02; // 2%概率
            } catch (error) {
                return false;
            }
        }
        
        giveRandomReward() {
            try {
                const rewards = [
                    () => this.giveCoins(10),
                    () => this.healPlayer(25),
                    () => this.giveAmmo(20)
                ];
                
                const reward = rewards[Math.floor(Math.random() * rewards.length)];
                reward();
                
            } catch (error) {
                this.log('随机奖励错误:', error.message);
            }
        }
        
        giveCoins(amount) {
            try {
                if (window.roguelikeSystem && 
                    typeof window.roguelikeSystem.addCurrency === 'function') {
                    window.roguelikeSystem.addCurrency(amount);
                    this.showNotification(`💰 获得 ${amount} 金币`);
                }
            } catch (error) {
                this.log('金币奖励错误:', error.message);
            }
        }
        
        healPlayer(amount) {
            try {
                if (window.player && window.player.health < window.player.maxHealth) {
                    window.player.health = Math.min(window.player.maxHealth, window.player.health + amount);
                    if (window.player.updateHealthUI) {
                        window.player.updateHealthUI();
                    }
                    this.showNotification(`❤️ 恢复 ${amount} 生命值`);
                }
            } catch (error) {
                this.log('治疗错误:', error.message);
            }
        }
        
        giveAmmo(amount) {
            try {
                if (window.player && window.player.currentWeapon) {
                    window.player.currentWeapon.totalAmmo += amount;
                    this.showNotification(`🔫 获得 ${amount} 弹药`);
                }
            } catch (error) {
                this.log('弹药奖励错误:', error.message);
            }
        }
        
        applyPermanentUpgrades() {
            try {
                if (!window.player) return;
                
                const upgrades = this.rogueData.permanentUpgrades;
                
                if (upgrades.healthBonus && upgrades.healthBonus > 0) {
                    window.player.maxHealth += upgrades.healthBonus * 10;
                    window.player.health = window.player.maxHealth;
                }
                
                if (upgrades.speedBonus && upgrades.speedBonus > 0) {
                    window.player.speed *= (1 + upgrades.speedBonus * 0.1);
                }
                
                this.log('✨ 应用永久升级');
                
            } catch (error) {
                this.log('永久升级应用错误:', error.message);
            }
        }
        
        scheduleEquipmentDrops(level) {
            try {
                const dropCount = Math.min(3, level);
                
                for (let i = 0; i < dropCount; i++) {
                    setTimeout(() => {
                        this.dropRandomEquipment();
                    }, Math.random() * 20000 + 5000);
                }
                
            } catch (error) {
                this.log('装备掉落安排错误:', error.message);
            }
        }
        
        completeRun() {
            try {
                const stats = this.rogueData.currentRunStats;
                
                // 更新最佳记录
                if (stats.levelsCompleted > this.rogueData.bestRun) {
                    this.rogueData.bestRun = stats.levelsCompleted;
                }
                
                this.rogueData.totalKills += stats.kills;
                
            } catch (error) {
                this.log('轮次完成错误:', error.message);
            }
        }
        
        giveDeathRewards() {
            try {
                const stats = this.rogueData.currentRunStats;
                
                // 基于表现给予永久升级
                if (stats.levelsCompleted >= 3) {
                    const upgrade = this.selectRandomPermanentUpgrade();
                    this.addPermanentUpgrade(upgrade);
                    this.showNotification(`🏆 获得永久升级: ${upgrade}`);
                }
                
                // 给予金币
                const coins = Math.floor(stats.levelsCompleted * 10);
                this.giveCoins(coins);
                
            } catch (error) {
                this.log('死亡奖励错误:', error.message);
            }
        }
        
        selectRandomPermanentUpgrade() {
            const upgrades = ['healthBonus', 'speedBonus', 'damageBonus'];
            return upgrades[Math.floor(Math.random() * upgrades.length)];
        }
        
        addPermanentUpgrade(upgradeType) {
            try {
                if (!this.rogueData.permanentUpgrades[upgradeType]) {
                    this.rogueData.permanentUpgrades[upgradeType] = 0;
                }
                this.rogueData.permanentUpgrades[upgradeType]++;
            } catch (error) {
                this.log('永久升级添加错误:', error.message);
            }
        }
        
        showDeathSummary() {
            try {
                const stats = this.rogueData.currentRunStats;
                const message = `
💀 第 ${this.rogueData.runCount} 轮结束
📊 关卡完成: ${stats.levelsCompleted}/10
🔫 敌人击杀: ${stats.kills}
🏆 最佳记录: ${this.rogueData.bestRun}
                `;
                
                this.showNotification('游戏结束', message, 5000);
                
            } catch (error) {
                this.log('死亡总结错误:', error.message);
            }
        }
        
        showLevelHint(level) {
            try {
                const hints = [
                    '🎯 新的挑战开始了！',
                    '🔫 寻找更好的装备',
                    '💎 击败敌人获得奖励',
                    '⚡ 选择合适的升级',
                    '🏆 向胜利前进！'
                ];
                
                const hint = hints[Math.min(level - 1, hints.length - 1)];
                this.showNotification(`关卡 ${level}`, hint);
                
            } catch (error) {
                this.log('关卡提示错误:', error.message);
            }
        }
        
        showNotification(title, message = '', duration = 3000) {
            try {
                this.log(`📢 ${title}: ${message}`);
                
                // 尝试创建视觉通知
                const notification = document.createElement('div');
                notification.style.cssText = `
                    position: fixed; top: 20px; right: 20px; z-index: 9999;
                    background: rgba(0,0,0,0.8); color: white; padding: 10px 15px;
                    border-radius: 5px; border: 1px solid #4CAF50;
                    font-size: 14px; max-width: 250px;
                `;
                notification.innerHTML = `<strong>${title}</strong><br>${message}`;
                
                document.body.appendChild(notification);
                
                setTimeout(() => {
                    try {
                        if (notification.parentNode) {
                            document.body.removeChild(notification);
                        }
                    } catch (e) {}
                }, duration);
                
            } catch (error) {
                // 静默失败，至少保证日志输出
            }
        }
        
        generateEquipmentName() {
            const prefixes = ['强化', '精良', '优质', '神秘'];
            const items = ['武器', '护甲', '药水', '弹药'];
            
            const prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
            const item = items[Math.floor(Math.random() * items.length)];
            
            return `${prefix}${item}`;
        }
        
        selectRarity() {
            const rand = Math.random();
            if (rand < 0.05) return 'legendary';
            if (rand < 0.2) return 'epic';
            if (rand < 0.4) return 'rare';
            return 'common';
        }
        
        resetRunStats() {
            return {
                startTime: Date.now(),
                kills: 0,
                damage: 0,
                levelsCompleted: 0
            };
        }
        
        // 数据持久化
        saveAllData() {
            try {
                Object.keys(this.rogueData).forEach(key => {
                    this.saveData(key, this.rogueData[key]);
                });
            } catch (error) {
                this.log('数据保存错误:', error.message);
            }
        }
        
        saveData(key, value) {
            try {
                localStorage.setItem(`roguelikeAddon_${key}`, JSON.stringify(value));
            } catch (error) {
                this.log(`数据保存失败 (${key}):`, error.message);
            }
        }
        
        loadData(key, defaultValue) {
            try {
                const saved = localStorage.getItem(`roguelikeAddon_${key}`);
                return saved ? JSON.parse(saved) : defaultValue;
            } catch (error) {
                this.log(`数据加载失败 (${key}):`, error.message);
                return defaultValue;
            }
        }
        
        log(...args) {
            if (ADDON_CONFIG.debug) {
                console.log('[RoguelikeAddon]', ...args);
            }
        }
        
        safeShutdown() {
            this.active = false;
            this.log('🔥 肉鸽系统已安全关闭');
        }
        
        // 公共API
        getStats() {
            return {
                runCount: this.rogueData.runCount,
                bestRun: this.rogueData.bestRun,
                totalKills: this.rogueData.totalKills,
                permanentUpgrades: this.rogueData.permanentUpgrades,
                currentRun: this.rogueData.currentRunStats
            };
        }
    }
    
    // 安全启动
    let roguelikeAddon = null;
    
    try {
        // 等待页面完全加载
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initializeAddon);
        } else {
            setTimeout(initializeAddon, 2000);
        }
        
        function initializeAddon() {
            try {
                roguelikeAddon = new RoguelikeAddon();
                window.roguelikeAddon = roguelikeAddon;
                console.log('🎲 肉鸽附加系统已加载');
            } catch (error) {
                console.error('🚫 肉鸽附加系统启动失败:', error);
            }
        }
        
        // 调试命令
        window.addEventListener('keydown', function(e) {
            if (e.ctrlKey && e.shiftKey && e.code === 'KeyR') {
                if (roguelikeAddon) {
                    console.log('🎲 肉鸽系统状态:', roguelikeAddon.getStats());
                }
            }
        });
        
    } catch (error) {
        console.error('🚫 肉鸽附加系统加载失败:', error);
    }
    
})();